#include "widget.h"
#include "ui_widget.h"
#include"QTreeWidget"
#include"QTreeWidgetItem"
#include"QList"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->treeWidget->setHeaderLabel("books");
    QTreeWidgetItem* name1=new QTreeWidgetItem();
    name1->setText(0,"小说");//第0列，名为小说
    QTreeWidgetItem* name2=new QTreeWidgetItem();
    name2->setText(0,"科技");
    QTreeWidgetItem* name3=new QTreeWidgetItem();
    name3->setText(0,"历史");
    ui->treeWidget->addTopLevelItems({name1,name2,name3});


}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addtop_clicked()
{

    QTreeWidgetItem* item=new QTreeWidgetItem();
    QString name=ui->lineEdit->text();
    item->setText(0,name);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_addchild_clicked()
{ QTreeWidgetItem* item=new QTreeWidgetItem();
  QString name=ui->lineEdit->text();
  if(name.isEmpty())
  {
      return;
  }

   item->setText(0,name);
  ui->treeWidget->currentItem()->addChild(item);
  ui->treeWidget->currentItem()->setExpanded(true);
}

void Widget::on_pushButton_del_clicked()
{
    QTreeWidgetItem* currentItem=  ui->treeWidget->currentItem();
    if (currentItem == NULL) {
     return;
     }
    QTreeWidgetItem* parent = currentItem->parent();
    if(parent==NULL)//判断是否为顶层节点
    {
        int index=ui->treeWidget->indexOfTopLevelItem(currentItem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
       {
        parent->removeChild(currentItem);//通过父亲节点删儿子节点

    }


}
